package com.qbm.association.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qbm.association.bean.*;
import com.qbm.association.config.Audience;
import com.qbm.association.entity.*;
import com.qbm.association.mapper.ClubMapper;
import com.qbm.association.mapper.StudentMapper;
import com.qbm.association.service.AdministratorService;
import com.qbm.association.service.ClubService;
import com.qbm.association.service.JoinClubService;
import com.qbm.association.service.StudentService;
import com.qbm.association.util.JWTTokenUtil;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Aron
 * @since 2022-02-07
 */
@RestController
@RequestMapping("/association/club")
public class ClubController {

    @Resource
    private ClubService clubService;

    @Resource
    private ClubMapper clubMapper;

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private JoinClubService joinClubService;

    @Autowired
    private Audience audience;

    @Resource
    private StudentService studentService;

    @Resource
    private AdministratorService administratorService;

    @GetMapping("getAllClubByStatus")
    public ResultBean getAllClubByStatus(Integer status) {
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("club_status", status);
        List<Club> list = clubService.list(queryWrapper);
        return ResultBean.success(list);
    }

    @GetMapping("getClubById")
    public ResultBean getClubById(Integer id) {
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        Club club = clubMapper.selectOne(queryWrapper);
        return ResultBean.success(club);
    }

    @GetMapping("getMyClub")
    public ResultBean getMyClub(HttpServletRequest request) {
        String token = request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY);
        String username = JWTTokenUtil.getUserName(token, audience.getBase64Secret());
        Student student = studentService.getByUsername(username);
        QueryWrapper<JoinClub> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", student.getId());
        List<JoinClub> listJoinClub = joinClubService.list(queryWrapper);
        List<Integer> temp = new ArrayList<>();
        for (JoinClub t : listJoinClub) {
            temp.add(t.getClubId());
        }
        List<Club> clubs = clubService.listByIds(temp);
        return ResultBean.success(clubs, "获取用户社团成功");
    }

    @PostMapping("addClub")
    public ResultBean addClub(Club club, HttpServletRequest request) {
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", club.getName());
        boolean isTrue = clubService.list(queryWrapper).size() == 0;
        Assert.isTrue(isTrue, "该社团已存在");
        club.setCreateUserId(studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret())).getId());
        club.setClubStatus(ClubStatusEnum.WAITING.getCode());
        isTrue = clubService.save(club);
        Assert.isTrue(isTrue, "申请失败");
        return ResultBean.success("申请成功，待审核");
    }

    /**
     * @param club
     * @return
     */
    @PostMapping("updateClub")
    public ResultBean updateClub(Club club) {
        boolean isTrue = clubService.updateById(club);
        Assert.isTrue(isTrue, "更新失败");
        return ResultBean.success("更新成功");
    }

    @PostMapping("deleteClub")
    public ResultBean deleteClub(Club club) {
        boolean isTrue = clubService.removeById(club);
        Assert.isTrue(isTrue, "删除失败");
        return ResultBean.success("删除成功");
    }

    @GetMapping("getPageClubByStatus")
    public ResultBean getPageClubByStatus(Integer status, Integer currentPage, String clubName) {
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        if (status != -1) {
            queryWrapper.eq("club_status", status);
        }
        if (clubName != null && clubName.length() != 0) {
            queryWrapper.like("name", clubName);
        }
        Page<Club> page = new Page<>(currentPage, 5);
        Page<Club> page1 = clubMapper.selectPage(page, queryWrapper);
        return ResultBean.success(page1, "获取成功");
    }

    /**
     * @param club
     * @return
     */
    @PostMapping("auditClub")
    public ResultBean auditClub(Club club, Integer userId, HttpServletRequest request) {
        String token = request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY);
        String username = JWTTokenUtil.getUserName(token, audience.getBase64Secret());
        Administrator byUsername = administratorService.getByUsername(username);
        club.setVerifierId(byUsername.getId());
        boolean isTrue = clubService.updateById(club);
        Assert.isTrue(isTrue, "审核失败");
        // 保存joinclub
        JoinClub joinClub = new JoinClub();
        joinClub.setClubId(club.getId());
        joinClub.setUserId(userId);
        joinClub.setUserPower(JoinClubPowerEnum.DIRECTOR.getCode());
        joinClub.setJoinClubStatus(JoinClubStatusEnum.SUCCESS.getCode());
        joinClubService.save(joinClub);
        return ResultBean.success("审核成功");
    }

    @GetMapping("getAllApplicantByStatus")
    public ResultBean getAllApplicantByStatus(Integer clubId, Integer status, Integer currentPage, String stuName) {
        if (status == -1) {
            status = null;
        }
        Page<Student> page = new Page<>(currentPage, 5);
        IPage<List<HashMap<Object, Object>>> page1 = clubMapper.getAllApplicantByStatus(
                page, clubId, JoinClubPowerEnum.MEMBER.getCode(), stuName, status);
        return ResultBean.success(page1, "获取成功");
    }

    @GetMapping("auditStu")
    public ResultBean auditStu(Integer joinClubId, Integer joinClubStatus, HttpServletRequest request) {
        JoinClub joinClub = new JoinClub();
        joinClub.setId(joinClubId);
        joinClub.setJoinClubStatus(joinClubStatus);
        boolean isTrue = joinClubService.updateById(joinClub);
        Assert.isTrue(isTrue, "审核失败");
        return ResultBean.success("审核成功");
    }

    @GetMapping("getClubManagerPageList")
    public ResultBean getClubManagerPageList(Integer currentPage, String clubName, HttpServletRequest request) {
        Integer id = studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret())).getId();
        // 可能是多个社团社长
        List<JoinClub> joinClubList = joinClubService.list(new QueryWrapper<JoinClub>().eq("user_id", id)
                .eq("user_power", JoinClubPowerEnum.DIRECTOR.getCode()));
        if (joinClubList.size() == 0) {// 社长数量为0则没有权限访问
            return ResultBean.fail("没有权限访问");
        }
        QueryWrapper<Club> queryWrapper = new QueryWrapper();
        if (clubName != null && clubName.length() != 0) {
            queryWrapper.like("name", clubName);
        }
        queryWrapper.and(wrapper -> {
            for (int i = 0; i < joinClubList.size(); i++) {
                if (i != joinClubList.size() - 1) {
                    wrapper.eq("id", joinClubList.get(i).getClubId()).or();
                } else {
                    wrapper.eq("id", joinClubList.get(i).getClubId());
                }
            }
        });
        queryWrapper.orderByDesc("create_time");
        Page<Club> page = new Page<>(currentPage, 5);
        Page<Club> page1 = clubMapper.selectPage(page, queryWrapper);
        return ResultBean.success(page1, "获取用户管理的社团成功");
    }

    @GetMapping("getClubMember")
    public ResultBean getClubMember(Integer clubId) {
        QueryWrapper<JoinClub> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("club_id", clubId)
                .eq("join_club_status", JoinClubStatusEnum.SUCCESS.getCode());
        List<JoinClub> joinClubList = joinClubService.list(queryWrapper);
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        for (int i = 0; i < joinClubList.size(); i++) {
            studentQueryWrapper.eq("id", joinClubList.get(i).getUserId()).or();
        }
        return ResultBean.success(studentService.list(studentQueryWrapper), "获取成功");
    }

    @GetMapping("getClubManager")
    public ResultBean getClubManager(Integer createUserId) {
        return ResultBean.success(studentService.list(new QueryWrapper<Student>().eq("id",createUserId)), "获取成功");
    }
}

